//
//  JSTHttpClient.m
//  JSTMobClick
//
//  Created by Czj on 16/8/28.
//  Copyright © 2016年 Czj. All rights reserved.
//

#import "JSTHttpClient.h"
#import <objc/runtime.h>
#import "KYDeviceInfoModel.h"

#define kErrorUserAuthenticationRequired    -4
#define kErrorClientCannotDecodeContentData 601

@implementation AFHTTPRequestOperationManager (requestMethod)

- (AFHTTPRequestOperation *)sendRequest:(NSString *)URLString
                          requestMethod:(NSString *)requestMethod
                             parameters:(id)parameters
                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:requestMethod URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    return operation;
}

@end

static inline NSString * HTTPUserAgent() {
    
    NSString *userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iPhone iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
    
    if (userAgent)
    {
        if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding])
        {
            NSMutableString *mutableUserAgent = [userAgent mutableCopy];
            if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false))
            {
                userAgent = mutableUserAgent;
            }
        }
    }
    return userAgent;
}

@implementation JSTHttpClient

+ (NSOperation *)sendRequest:(NSString *)url
               requestMethod:(NSString *)requestMethod
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(id responseObject))success
                     failure:(void (^)(NSUInteger statusCode, NSString *error))failure
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
#if !TARGET_ENV_PRD
    manager.securityPolicy.allowInvalidCertificates = YES;  // 测试环境允许无效证书
#endif
    
    // 设置请求
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    requestSerializer.timeoutInterval = 15;
    NSString *userAgent = HTTPUserAgent();
    [requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    [requestSerializer setValue:userAgent forHTTPHeaderField:@"eppUserAgent"];
    manager.requestSerializer = requestSerializer;
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    // 设置响应
    AFHTTPResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:responseSerializer.acceptableContentTypes];
    [acceptableContentTypes addObject:@"text/html"];
    [acceptableContentTypes addObject:@"text/json"];
    [acceptableContentTypes addObject:@"application/json"];
    responseSerializer.acceptableContentTypes = acceptableContentTypes;
    manager.responseSerializer = responseSerializer;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSOperation *operation = [manager sendRequest:url requestMethod:requestMethod parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSError *err = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&err];
        if(!err){if (success){success(dict);}}
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSString *tError = nil;
        switch ([error code]) {
            case NSURLErrorTimedOut:
                tError = [NSString stringWithFormat:@"连接服务器超时, 请检查你的网络或稍后重试"];
                break;
            case NSURLErrorBadURL:
            case NSURLErrorUnsupportedURL:
            case NSURLErrorCannotFindHost:
            case NSURLErrorDNSLookupFailed:
            case NSURLErrorCannotConnectToHost:
            case NSURLErrorNetworkConnectionLost:
            case NSURLErrorNotConnectedToInternet:
            case NSURLErrorUserCancelledAuthentication:
            case NSURLErrorUserAuthenticationRequired:
            case NSURLErrorSecureConnectionFailed:
            case NSURLErrorServerCertificateHasBadDate:
            case NSURLErrorServerCertificateUntrusted:
            case NSURLErrorServerCertificateHasUnknownRoot:
            case NSURLErrorServerCertificateNotYetValid:
            case NSURLErrorClientCertificateRejected:
            case NSURLErrorClientCertificateRequired:
                tError = [NSString stringWithFormat:@"无法连接到服务器, 请检查你的网络或稍后重试"];
                break;
            case NSURLErrorHTTPTooManyRedirects:
                tError = [NSString stringWithFormat:@"太多HTTP重定向, 请检查你的网络或稍后重试"];
                break;
            default:
                tError = [NSString stringWithFormat:@"系统繁忙，请稍后再试"];
                break;
        }
        if (failure) failure([error code], tError);
        NSString *result  =[[ NSString alloc] initWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        NSLog(@"%@",result);
    }];
    return operation;
}

//上传多张图片
+ (NSOperation *)sendRequest:(NSString *)url
               requestMethod:(NSString *)requestMethod
                  parameters:(NSDictionary *)parameters
                  imageArray:(NSArray *)imageArray
                     success:(void (^)(id responseObject))success
                     failure:(void (^)(NSUInteger statusCode, NSString *error))failure
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
#if !TARGET_ENV_PRD
    manager.securityPolicy.allowInvalidCertificates = YES;  // 测试环境允许无效证书
#endif
    
    // 设置请求
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    requestSerializer.timeoutInterval = 28;
    NSString *userAgent = HTTPUserAgent();
    [requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    [requestSerializer setValue:userAgent forHTTPHeaderField:@"eppUserAgent"];
    manager.requestSerializer = requestSerializer;
    
    // 设置响应
    AFHTTPResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:responseSerializer.acceptableContentTypes];
    
    [acceptableContentTypes addObject:@"text/html"];
    [acceptableContentTypes addObject:@"text/json"];
    [acceptableContentTypes addObject:@"application/json"];
    [acceptableContentTypes addObject:@"image/jpeg"];
    [acceptableContentTypes addObject:@"image/png"];
    responseSerializer.acceptableContentTypes = acceptableContentTypes;
    manager.responseSerializer = responseSerializer;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    AFHTTPRequestOperation *operation = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                         {
                                             if ([url containsString:@"index.edit_userinfo"])
                                             {
                                                 if (IsArrEmpty(imageArray))
                                                 {
                                                     return;
                                                 }
                                                 NSData *imageData = UIImageJPEGRepresentation(imageArray[0], 0.01);
                                                 //上传的参数名
                                                 NSString *name = @"icon";
                                                 //上传的filename
                                                 NSString *fileName = [NSString stringWithFormat:@"%@.jpeg",name];
                                                 
                                                 [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
                                             }else
                                             {
                                                 for (int i=0; i < imageArray.count; i++)
                                                 {
                                                     NSData *imageData = UIImageJPEGRepresentation(imageArray[i], 0.01);
                                                     //上传的参数名
                                                     NSString *name = [NSString stringWithFormat:@"kyImage%d",i+1];
                                                     //上传的filename
                                                     NSString *fileName = [NSString stringWithFormat:@"%@.jpeg",name];
                                                     
                                                     [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
                                                 }
                                             }
                                             
                                             
                                         } success:^(AFHTTPRequestOperation *operation, id responseObject)
                                         {
                                             if (!responseObject)
                                             {
                                                 NSInteger errorCode = kErrorClientCannotDecodeContentData;
                                                 NSString *errorMsg = @"The response data cannot be decoded.";
                                                 
//                                                 NSLog(@"\n%@ FAILED: \n%@\nERROR_CODE: %ld\nERROR: %@", requestMethod, [url urlByAppendingDict:parameters], (long)errorCode, errorMsg);
                                                 
                                                 NSString *tError = [NSString stringWithFormat:@"系统繁忙，请稍后再试"];
                                                 
                                                 if (failure)
                                                 {
                                                     failure(errorCode, tError);
                                                 }
                                             }
                                             else
                                             {
                                                 if (success)
                                                 {
                                                     NSError *err = nil;
                                                     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&err];
                                                     if(!err){if (success){success(dict);}}
                                                 }
                                             }
                                         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                             
                                             NSString *tError = nil;
                                             
                                             switch ([error code]) {
                                                     
                                                 case NSURLErrorTimedOut:
                                                     tError = [NSString stringWithFormat:@"连接服务器超时, 请检查你的网络或稍后重试"];
                                                     break;
                                                 case NSURLErrorBadURL:
                                                 case NSURLErrorUnsupportedURL:
                                                 case NSURLErrorCannotFindHost:
                                                 case NSURLErrorDNSLookupFailed:
                                                 case NSURLErrorCannotConnectToHost:
                                                 case NSURLErrorNetworkConnectionLost:
                                                 case NSURLErrorNotConnectedToInternet:
                                                 case NSURLErrorUserCancelledAuthentication:
                                                 case NSURLErrorUserAuthenticationRequired:
                                                 case NSURLErrorSecureConnectionFailed:
                                                 case NSURLErrorServerCertificateHasBadDate:
                                                 case NSURLErrorServerCertificateUntrusted:
                                                 case NSURLErrorServerCertificateHasUnknownRoot:
                                                 case NSURLErrorServerCertificateNotYetValid:
                                                 case NSURLErrorClientCertificateRejected:
                                                 case NSURLErrorClientCertificateRequired:
                                                     tError = [NSString stringWithFormat:@"无法连接到服务器, 请检查你的网络或稍后重试"];
                                                     break;
                                                     
                                                 case NSURLErrorHTTPTooManyRedirects:
                                                     tError = [NSString stringWithFormat:@"太多HTTP重定向, 请检查你的网络或稍后重试"];
                                                     break;
                                                     
                                                 default:
                                                     tError = [NSString stringWithFormat:@"系统繁忙，请稍后再试"];
                                                     break;
                                             }
//                                             NSLog(@"\n%@ FAILED: \n%@\nERROR_CODE: %ld\nERROR: %@", requestMethod, [url urlByAppendingDict:parameters], (long)[error code], tError);
                                             if (failure)
                                             {
                                                 failure([error code], tError);
                                             }
                                             
                                         }];
    
    return operation;
    
}
+ (NSMutableDictionary *)uaDic{
    NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
    unsigned int count = 0;
    KYDeviceInfoModel *model = [KYDeviceInfoModel deviceInfoModel];
    objc_property_t *properties = class_copyPropertyList([model class], &count);
    for (int i = 0; i < count; i++) {
        const char *name = property_getName(properties[i]);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id propertyValue = [model valueForKey:propertyName];
        if (propertyValue) {
            [userDic setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return userDic;
}

@end
